﻿using System;
using System.IO;
using Htm2Pdf.Common.Interfaces;

namespace Htm2Pdf.Convertor
{
    public class FoldersManager
    {
        private IDatabase _db;
        private string _pdfsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "pdfs");
        private string _alphabet = "abcdeefghijklmnopqrstuvwzx";
        private const int FolderLength = 10;

        public FoldersManager(IDatabase db)
        {
            _db = db;
        }

        private string GetNewFolderName()
        {
            Random rnd = new Random();

            string res = "";

            for (int i = 0; i < FolderLength - 1; i++)
            {
                int letterIndex = rnd.Next(0, _alphabet.Length - 1);

                string letter = _alphabet[letterIndex].ToString();

                bool upper = rnd.Next(-5, 5) > 0;
                if (upper) letter = letter.ToUpper();

                res += letter;

            }


            return res;
        }


        public string CreateFolder()
        {
            string res;
            
            while (true)
            {
                 string newFolder = GetNewFolderName();

                 if (_db.FolderExists(newFolder) == false)
                 {
                     _db.AddFolder(newFolder);

                     DirectoryInfo dir = new DirectoryInfo(_pdfsFolder);
                     dir.CreateSubdirectory(newFolder);
                     res = newFolder;
                     break;
                 }
            }


            return Path.Combine(_pdfsFolder, res) ;
        }


    }
}
